package com.example.kcb;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class CourseRecordsActivity extends AppCompatActivity {
    private CourseRecordAdapter adapter;
    private List<CourseRecords> courseRecordsList = new ArrayList<>();

    private TextView tvStartDate;
    private TextView tvEndDate;
    private DatabaseHelper databaseHelper = new DatabaseHelper
            (this);

    private Calendar cal = Calendar.getInstance();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_course_records);

        /* 1. 找到控件 */
        ListView listView = (ListView) findViewById(R.id.listView);
        tvStartDate = (TextView) findViewById(R.id.tv_start_date);
        tvEndDate   = (TextView) findViewById(R.id.tv_end_date);

        /* 2. 初始化 Adapter 并绑定 ListView（只做一次） */
        adapter = new CourseRecordAdapter(this,
                R.layout.custom_list_item,
                courseRecordsList);
        listView.setAdapter(adapter);

        /* 3. 默认日期 */
        Calendar now = Calendar.getInstance();
        updateDateText(now, tvStartDate, true);
        updateDateText(now, tvEndDate,   false);
    }
    /* ---------------- 弹出日期选择器（仅回写文字） ---------------- */
    public void onStartDateClicked(View v) {
        showDatePicker(tvStartDate, true);
    }

    public void onEndDateClicked(View v) {
        showDatePicker(tvEndDate, false);
    }

    private void showDatePicker(TextView target, boolean isStart) {
        DatePickerDialog dialog = new DatePickerDialog(
                this,
                android.app.AlertDialog.THEME_HOLO_LIGHT,
                (view, y, m, d) -> {
                    Calendar c = Calendar.getInstance();
                    c.set(y, m, d);
                    updateDateText(c, target, isStart);
                    // 注意：这里不再调用 loadData()
                },
                cal.get(Calendar.YEAR),
                cal.get(Calendar.MONTH),
                cal.get(Calendar.DAY_OF_MONTH)
        );
        dialog.setTitle(isStart ? "选择开始日期" : "选择结束日期");
        dialog.show();
    }

    /* ---------------- 真正查库 ---------------- */
    public void loadData(String startDateStr, String endDateStr) {
        courseRecordsList.clear();          // 清空旧数据

        SQLiteDatabase db = databaseHelper.getReadableDatabase();
        Cursor cursor = db.query("course_records", null,
                "record_time >= ? AND record_time <= ?",
                new String[]{startDateStr, endDateStr},
                null, null, null);

        while (cursor.moveToNext()) {
            CourseRecords r = new CourseRecords();
            r.setCourseName(cursor.getString(cursor.getColumnIndex("course_name")));
            r.setClassRoom(cursor.getString(cursor.getColumnIndex("class_room")));
            r.setTeacher(cursor.getString(cursor.getColumnIndex("teacher")));
            r.setRecordTime(cursor.getString(cursor.getColumnIndex("record_time")));
            r.setPeriod(cursor.getString(cursor.getColumnIndex("period")));
            r.setDay(cursor.getInt(cursor.getColumnIndex("date")));
            courseRecordsList.add(r);
        }
        cursor.close();

        /* 5. 通知 Adapter 刷新界面（千万别再 new Adapter） */
        adapter.notifyDataSetChanged();
    }
    /* ---------------- 查询按钮 ---------------- */
    public void onQueryClicked(View v) {
        String start = tvStartDate.getText().toString();
        String end   = tvEndDate.getText().toString();
        if (start.isEmpty() || end.isEmpty()) {
            Toast.makeText(this, "请选择日期范围", Toast.LENGTH_SHORT).show();
            return;
        }

        /* 4. 查数据库 -> 把结果写进 courseRecordsList */
        loadData(start, end);
    }

    // 在 MainActivity 或任意触发“课程统计”的地方
    public void onSumClicked(View v) {
        Intent i = new Intent(this, CourseStatActivity.class);
        i.putExtra("start", tvStartDate.getText().toString());  // 2025-09-01
        i.putExtra("end",   tvEndDate.getText().toString());    // 2025-09-30
        startActivity(i);
    }
    /* ---------------- 工具：把日历转成文字 ---------------- */
    private void updateDateText(Calendar c, TextView tv, boolean isStart) {
        String fmt = String.format("%04d-%02d-%02d",
                c.get(Calendar.YEAR),
                c.get(Calendar.MONTH) + 1,
                c.get(Calendar.DAY_OF_MONTH));
        tv.setText(isStart ? fmt: fmt);
    }
}
